<template>
	<div>
		<el-tree
			ref="treeRef"
			:data="configure.source"
			:node-key="configure.nodeKey"
			:lazy="!!configure.lazy"
			:load="configure.lazy ? load : () => {}"
			:default-expand-all="configure.expand"
			:props="defaultProps"
			show-checkbox
			@check="configure.change"
		/>
	</div>
</template>

<script setup lang="ts">
import { ElTree } from "element-plus";
import { TreeData, TreeOptions } from "./type";
import { Ref, onMounted, ref } from "vue";
import type Node from "element-plus/es/components/tree/src/model/node";

const props = defineProps<{
	configure: TreeOptions;
	init: (treeRef: InstanceType<typeof ElTree> | null) => void;
}>();

const treeRef: Ref<InstanceType<typeof ElTree> | null> = ref(null);
const allowDisabling = ref(props.configure.allowDisabling === false ? false : true);

const defaultProps: any = {
	disabled: function (data: TreeData) {
		return allowDisabling.value && !data.value && data.value !== 0;
	},
};

const load = (node: Node, resolve: (data: any[]) => void) => {
	if (node.level === 0) {
		return resolve(node.data as TreeData[]);
	} else if (props.configure.lazy) {
		return props.configure.lazy.load(node, resolve);
	}
};

onMounted(() => {
	props.init(treeRef.value);
});
</script>

<style lang="scss" scoped></style>
